package com.yf.controller.api;

import com.yf.annotation.IgnoreAuth;
import com.yf.entity.TokenEntity;
import com.yf.entity.UserEntity;
import com.yf.entity.WxUser;
import com.yf.response.R;
import com.yf.service.TokenService;
import com.yf.service.UserService;
import com.yf.service.WxAppService;
import com.yf.service.WxWebService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("/api")
public class ApiLoginController {

    /**
     * 微信公众号获取code
     * @return
     */
    @RequestMapping("/wx/code")
    @IgnoreAuth
    public void wxCode(String backUrl, HttpServletResponse response) throws IOException {
        String codeUrl = wxWebService.getCodeUrl(backUrl);
        //带上code之后会跳转回去
        response.sendRedirect(codeUrl);
    }

    /**
     * 微信公众号登录
     * @param code
     * @param parentId
     * @return
     */
    @RequestMapping("/wx/web/login")
    @IgnoreAuth
    public R wxWebLogin(String code,@RequestParam(required = false) Long parentId){
        TokenEntity token;
        WxUser wxUser = wxWebService.getWxUser(code);
        UserEntity userEntity = userService.findByUnionId(wxUser.getUnionId());
        if (userEntity == null) {
            token = userService.registerUser(wxUser, parentId);
        } else {
            //更新用户
            userEntity.setOpenId(wxUser.getOpenId());
            userEntity.setPayId(wxUser.getOpenId());
            userEntity.setAvatar(wxUser.getHeadImgUrl());
            userService.update(userEntity);
            token = userService.validateLogin(userEntity);
        }
        return R.ok("登录成功", token).putExtra("wxUser",wxUser);
    }


    /**
     * 小程序登录 关注过才能返回UnionId
     *
     * @param code
     * @param parentId
     * @return
     */
    @RequestMapping("/wx/login")
    @IgnoreAuth
    public R wxLogin(String encryptedData, String code, String iv, @RequestParam(required = false) Long parentId) {
        TokenEntity token;
        //先获取key
        WxUser wxUser = wxAppService.getOpenIdAndSessionKey(code);
        wxUser = wxAppService.getWxUser(encryptedData, wxUser.getSessionKey(), iv);
        UserEntity userEntity = userService.findByUnionId(wxUser.getUnionId());
        if (userEntity == null) {
            token = userService.registerUser(wxUser, parentId);
        } else {
            token = userService.validateLogin(userEntity);
        }
        return R.ok("登录成功", token);
    }

    /**
     * 获取token
     * @param
     * @param
     * @return
     */
    @RequestMapping("/wx/testLogin")
    @IgnoreAuth
    public R testLogin(Long userId){
        TokenEntity token = tokenService.createToken(userId);
        WxUser wxUser = new WxUser();
        UserEntity userEntity = userService.get(token.getUserId());
        wxUser.setHeadImgUrl(userEntity.getAvatar());
        wxUser.setNickName(userEntity.getName());
        return R.ok("登录成功", token).putExtra("wxUser",wxUser);
    }

    /**
     * 账号（手机）密码登陆
     * @param
     * @param
     * @return
     */
    @RequestMapping("/phone/login")
    @IgnoreAuth
    public R login(String phone,String password){
        UserEntity userEntity = userService.login(phone,password);
        if(userEntity!=null){
            TokenEntity token = tokenService.createToken(userEntity.getId());
            return R.ok("登录成功", token);
        }else {
            return R.error("账号密码有误，请重试");
        }

    }

    /**
     * 注册
     * @param
     * @param
     * @return
     */
   /* @RequestMapping("/phone/register")
    @IgnoreAuth
    public R register(String phone,String password,String name){
        UserEntity userEntity = userService.registerUser(phone,password,name);
        if(userEntity!=null){
            TokenEntity token = tokenService.createToken(userEntity.getId());
            return R.ok("登录成功", token);
        }else {
            return R.error("账号密码有误，请重试");
        }

    }*/


    @Autowired
    private UserService userService;


    @Autowired
    private WxAppService wxAppService;

    @Autowired
    private WxWebService wxWebService;

    @Autowired
    private TokenService tokenService;

}
